package com.codingfly.controller;

import cn.hutool.core.bean.BeanUtil;
import com.codingfly.controller.common.BaseController;
import com.codingfly.core.exception.BizException;
import com.codingfly.core.util.AssertUtils;
import com.codingfly.core.util.TreeListUtils;
import com.codingfly.entity.SysMenu;
import com.codingfly.model.Result;
import com.codingfly.model.dto.MemuDto;
import com.codingfly.model.vo.MemuVo;
import com.codingfly.service.SysMenuService;
import com.codingfly.service.impl.CommonServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/menu")
public class MenuController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(MenuController.class);
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private CommonServiceImpl commonServiceImpl;


    @PostMapping
    public Result add(@RequestBody MemuDto dto) {
        checkParams(dto, "name", "code", "parentId", "auditTime");
        AssertUtils.isTrue(sysMenuService.findByCode(dto.getCode())==null, "该code编码 "+dto.getCode()+" 的数据已存在");
        SysMenu parent = Optional.ofNullable(sysMenuService.findById(dto.getParentId())).orElseThrow(()->new BizException("父节点不存在或者已删除"));
        SysMenu sysMenu = new SysMenu();
        sysMenu.setName(dto.getName());
        sysMenu.setCode(dto.getCode());
        sysMenu.setAuditTime(dto.getAuditTime());
        sysMenu.setParentId(dto.getParentId());
        sysMenu.setOrderNo(commonServiceImpl.queryNextOrderNoInt("sys_menu"));
        sysMenuService.save(sysMenu);
        Long id = sysMenu.getId();
        sysMenu.setFullPath(parent.getFullPath()+","+id);
        sysMenuService.save(sysMenu);
        return Result.success();
    }

    @PutMapping("/{id}")
    public Result update(@PathVariable("id") Long id, @RequestBody MemuDto dto) {
        checkParams(dto, "code", "name", "auditTime");
        SysMenu sysMenu = Optional.ofNullable(sysMenuService.findById(id)).orElseThrow(()->new BizException("该节点不存在或者已删除"));
        if (!dto.getCode().equals(sysMenu.getCode())) {
            AssertUtils.isTrue(sysMenuService.findByCode(dto.getCode())==null, "该CODE编码 "+dto.getCode()+" 已存在");
        }
        sysMenu.setCode(dto.getCode());
        sysMenu.setName(dto.getName());
        sysMenu.setAuditTime(dto.getAuditTime());
        sysMenuService.save(sysMenu);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable("id") Long id) {
        AssertUtils.isTrue(sysMenuService.hasChildren(id), "请先删除子节点");
        sysMenuService.deleteById(id);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<SysMenu> queryById(@PathVariable("id") Long id) {
        return Result.success(sysMenuService.findById(id));
    }

    @GetMapping("/treeList")
    public Result<List<SysMenu>> queryTreeList() {
        List<SysMenu> sysMenus = sysMenuService.findAll();
        List<MemuVo> menuVos = BeanUtil.copyToList(sysMenus, MemuVo.class);
        menuVos = TreeListUtils.buildAscTreeList(menuVos, "id", "parentId", "children", "orderNo");
        return Result.success(menuVos);
    }

    @PatchMapping("/move/{id}")
    public Result move(@PathVariable("id") Integer id, @RequestParam("action") String action) {
        if ("up".equals(action)) {
            commonServiceImpl.upOrderNoHasParent("sys_menu", id);
        } else if ("down".equals(action)) {
            commonServiceImpl.downOrderNoHasParent("sys_menu", id);
        }
        return Result.success();
    }
}
